package cn.whitecao.agent.core.repoter.impl;

import cn.whitecao.agent.core.model.Span;
import cn.whitecao.agent.core.repoter.Reporter;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 *  okhttp 方式上报
 * @author Bashful Huang
 * @since 2020-09-15
 **/
public class OkhttpReporter implements Reporter {
    private String reportUrl;
    /**
     * 单条上报
     *
     * @param span 采集数据的实体
     */
    @Override
    public void report(Span span) {
        report(Collections.singletonList(span));
    }

    /**
     * 多条上报
     *
     * @param spanList 采集数据的实体列表
     */
    @Override
    public void report(List<Span> spanList) {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(spanList));
            Request request = new Request.Builder()
                    .url(this.reportUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void init(String url){
        this.reportUrl=url;
    }
}